console.log('央视新闻注入');

(function (xhr) {
  if (XMLHttpRequest.prototype.hasChange) return;
  var XHR = XMLHttpRequest.prototype;
  XHR.hasChange = true;
  var open = XHR.open;
  var send = XHR.send;
  XHR.open = function (method, url) {
    this._method = method; // 记录method和url
    this._url = url;
    return open.apply(this, arguments);
  };
  XHR.send = function () {
    const videoUrls = [
      "https://res.cctvnews.cctv.com/video/",
      "https://cms-emer-res.cctvnews.cctv.com/cctv/video/"
    ];
    let filterResult = videoUrls.filter(url => this._url.includes(url)).length > 0 ? true : false;
    if (filterResult) {
        this.addEventListener("load", function (xhr) {
          // console.log('xhr', xhr)
          if (xhr.currentTarget._url.endsWith('.m3u8') && xhr.currentTarget.status === 200 && xhr.currentTarget.readyState === 4){
            let baseUrl = `${xhr.currentTarget._url.slice(0, xhr.currentTarget._url.lastIndexOf('/'))}/`;
            // console.log(baseUrl)
            let m3u8Arr = xhr.currentTarget.response.split('\n').filter(item => item.endsWith('.ts'));
            // console.log(m3u8Arr)
            // let m3u8Urls = m3u8Arr.map(fileName => `${baseUrl}${fileName}`);
            m3u8Arr.forEach(fileName => {
              download(baseUrl, fileName);
            })
          }
        });
    }
    return send.apply(this, arguments);
  };
})(XMLHttpRequest);

function download(baseUrl, filename){
  const xhr = new XMLHttpRequest();
  xhr.open('get', `${baseUrl}${filename}`, true);
  xhr.responseType = 'blob';
  xhr.send();
  xhr.onload = function (){
    let blob,
        a,
        fileUrl;
    if (this.status >= 200 && this.status < 300 || this.status === 304){
      blob = new Blob([this.response]);
      a = document.createElement('a');
      fileUrl = window.URL.createObjectURL(blob);
      a.href = fileUrl;
      a.download = filename;
      a.click();

    }
  }
}
/*
  "content_scripts": [
    {
      "matches": ["https://ysxw.cctv.cn/*"],
      "js": [
        "./contents/ysxw/ysxw.js"
      ],
      "run_at": "document_start",
      "world": "MAIN"
    }
  ],
  "host_permissions": [
    "https://ysxw.cctv.cn/*"
  ]
*/
